package com.jiamao.goplay.ui.login.vm;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResLogin;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.login.AddBasicInfoFragment;
import com.jiamao.goplay.ui.login.LoginPhoneSMSFragment;
import com.jiamao.goplay.ui.login.RegiestActivity;
import com.jiamao.goplay.ui.login.RetrievePwdActivity;
import com.jiamao.goplay.ui.main.MainActivity;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.tamsiree.rxkit.view.RxToast;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by goldze on 2017/7/17.
 */

public class LoginViewModel extends BaseViewModel<DataRepository> {
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    //密码的绑定
    public ObservableField<String> password = new ObservableField<>("");

    //密码的绑定
    public ObservableField<String> resmsTime = new ObservableField<>("");

    public ObservableField<String> smsPhone = new ObservableField<>("");

    //用户名清除按钮的显示隐藏绑定
    public ObservableInt clearBtnVisibility = new ObservableInt();

    public ObservableBoolean btnClickEndbel = new ObservableBoolean();

    public ObservableField<String> smscode = new ObservableField<>("");

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();

        public SingleLiveEvent<Boolean> reBtnGetCode = new SingleLiveEvent<>();
    }

    public LoginViewModel(@NonNull Application application, DataRepository repository) {
        super(application, repository);
        //从本地取得数据绑定到View层
        userName.set(model.getUserName());
        password.set(model.getPassword());



    }
    //登录按钮的点击事件
    public BindingCommand backOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });
    //清除用户名的点击事件, 逻辑从View层转换到ViewModel层
    public BindingCommand clearUserNameOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            userName.set("");
        }
    });
    //密码显示开关  (你可以尝试着狂按这个按钮,会发现它有防多次点击的功能)
    public BindingCommand passwordShowSwitchOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
            uc.pSwitchEvent.setValue(uc.pSwitchEvent.getValue() == null || !uc.pSwitchEvent.getValue());
        }
    });
    //用户名输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusChangeCommand = new BindingCommand<>(new BindingConsumer<Boolean>() {
        @Override
        public void call(Boolean hasFocus) {
            if (hasFocus) {
                clearBtnVisibility.set(View.VISIBLE);
            } else {
                clearBtnVisibility.set(View.INVISIBLE);
            }
        }
    });

    //密码输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusPwdChangeCommand = new BindingCommand<>(new BindingConsumer<Boolean>() {
        @Override
        public void call(Boolean hasFocus) {
            if (hasFocus) {
                clearBtnVisibility.set(View.VISIBLE);
            } else {
                clearBtnVisibility.set(View.INVISIBLE);
            }
        }
    });
    //密码登录按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            login();
        }
    });


    //登录手机号按钮的点击事件
    public BindingCommand loginPhoneOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            loginPhone();
        }
    });

    //登录按钮的点击事件
    public BindingCommand loginPhoneReGetSMSCodeOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            model.getApi().sendSMS(userName.get(),1)
                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                    .compose(RxUtils.schedulersTransformer())  // 线程调度
                    //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                    //    .doOnSubscribe(this) //请求与ViewModel周期同步
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                            // dialog.show();
                        }
                    })
                    .subscribe(new DisposableObserver<BaseRep>() {
                        @Override
                        public void onNext(BaseRep baseRep) {
                            dismissDialog();
                            // dialog.dismiss();
                            //保存账号密码
                            if (baseRep.isOk()){
//                                uc.reBtnGetCode.setValue(false);
                                reTimeSmsCode();
                            }else {
                                RxToast.showToastShort(baseRep.getMsg());
//
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            dismissDialog();
                            e.printStackTrace();
                            RxToast.showToastShort("网络出现故障");
                        }

                        @Override
                        public void onComplete() {
                            dismissDialog();
                        }

                    });

        }
    });

    //登录按钮的点击事件
    public BindingCommand regiestPostOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //    login();
        }
    });



    //登录按钮的点击事件
    public BindingCommand regiestOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
           // login();
            startActivity(RegiestActivity.class);
        }
    });


    //登录按钮的点击事件
    public BindingCommand retrievePwdOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(RetrievePwdActivity.class);

        }
    });


    public void addTextEditFoush(){

        if (userName.get().length()== 11 && password.get().length()>=6){
            btnClickEndbel.set(true);
        }else {
            btnClickEndbel.set(false);
        }
    }

    /**
     * 网络模拟一个登陆操作
     **/
    private void login() {
        if (TextUtils.isEmpty(userName.get())) {
            ToastUtils.showShort("请输入账号！");
            return;
        }
        if (TextUtils.isEmpty(password.get())) {
            ToastUtils.showShort("请输入密码！");
            return;
        }
//        RxPermissions rxPermissions = new RxPermissions((Activity) context);
//        RetrofitClient.getInstance().create(ApiService.class)
//                .demoGet()
//                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
//                .compose(RxUtils.schedulersTransformer())  // 线程调度
//                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
//                .subscribe(new Consumer<BaseResponse<DemoEntity>>() {
//                    @Override
//                    public void accept(BaseResponse<DemoEntity> response) throws Exception {
//
//                    }
//                }, new Consumer<ResponseThrowable>() {
//                    @Override
//                    public void accept(ResponseThrowable throwable) throws Exception {
//
//                    }
//                });

//        addSubscribe(model.login()
//            //    .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
//                .compose(RxUtils.schedulersTransformer())  // 线程调度
//           //     .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Exception {
//                        showDialog();
//                       // dialog.show();
//                    }
//                })
//                .subscribe(new Consumer<Object>() {
//                    @Override
//                     public void accept(Object o) throws Exception {
//                        dismissDialog();
//                      // dialog.dismiss();
//                        //保存账号密码
//                        model.saveUserName(userName.get());
//                        model.savePassword(password.get());
//                        //进入DemoActivity页面
//                        startActivity(MainActivity.class);
//                        //关闭页面
//                       finish();
//                    }
//                }));

    }


    /**
     * 网络模拟一个登陆操作
     **/
    private void loginPhone() {
        if (TextUtils.isEmpty(userName.get())) {
            ToastUtils.showShort("请输入账号！");
            return;
        }

        model.getApi().sendSMS(userName.get(),1)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
             //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
            //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new DisposableObserver<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {
                        dismissDialog();
                        // dialog.dismiss();
                        //保存账号密码
                        if (baseRep.isOk()){
                            model.saveUserName(userName.get());
                            Bundle bundle = new Bundle();
                            bundle.putString("phone",userName.get());
                            startContainerActivity(LoginPhoneSMSFragment.class.getCanonicalName(),bundle);
                        }else {
                          RxToast.showToastShort(baseRep.getMsg());
//                            TipDialog.show(get, "成功！", TipDialog.TYPE.SUCCESS)
//                                    .setTipTime(5000);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }

                });

    }


    /**
     * 网络模拟一个登陆操作
     **/
    public void loginSendSMS(String phone,String sms) {


        model.getApi().loginPhone(phone,sms)

                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new DisposableObserver<BaseRep<ResLogin>>() {

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        //请求刷新完成收回
                        RxToast.showToastShort(throwable.getMessage());

                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }

                    @Override
                    public void onNext(BaseRep<ResLogin> o)   {
                        dismissDialog();
                        if (o.isOk()){
                            model.getmLocalDataSource().saveImToken(o.getData().getIMToken());
                            model.getmLocalDataSource().saveToken(o.getData().getToken());
                            model.getmLocalDataSource().saveUid(o.getData().getUid());
                            model.getmLocalDataSource().saveSex(o.getData().getGender());
                            if(o.getData().getIsPerfect() == 0){
                                   KLog.d("HTML","进入资料编辑页面");
                                 startContainerActivity(AddBasicInfoFragment.class.getCanonicalName());
                                 finish();
                            }
                            else {
                                KLog.d("HTML","进入首页等公路");
                                model.saveUserName(phone);
                                Log.d("HTML","UID:"+model.getmLocalDataSource().getUid()+"  token:"+ model.getmLocalDataSource().getIMToken());
                                 NimUIKit.login(new LoginInfo(model.getmLocalDataSource().getUid()+"", model.getmLocalDataSource().getIMToken()), new RequestCallback<LoginInfo>() {
                                    @Override
                                    public void onSuccess(LoginInfo param) {

                                        SPUtils.getInstance().put(Config.IS_LOGIN,true);
                                        startActivity(MainActivity.class);
                                        finish();
                                    }

                                    @Override
                                    public void onFailed(int code) {
                                        RxToast.showToastShort("IM服务器登陆失败"+code);
//                                        if (code == 302 || code == 404) {
//                                            RxToast.showToastShort("IM 登录失败");
//                                            Toast.makeText(LoginActivity.this, R.string.login_failed, Toast.LENGTH_SHORT).show();
//                                        } else {
//                                            Toast.makeText(LoginActivity.this, "登录失败: " + code, Toast.LENGTH_SHORT).show();
//                                        }
                                    }

                                    @Override
                                    public void onException(Throwable exception) {
                                        RxToast.showToastShort("IM 登录异常"+exception.getMessage());
                                    }
                                });
//                                LoginInfo info = new LoginInfo(model.getmLocalDataSource().getUid()+"",model.getmLocalDataSource().getIMToken());
//                                RequestCallback<LoginInfo> callback =
//                                        new RequestCallback<LoginInfo>() {
//                                            @Override
//                                            public void onSuccess(LoginInfo param) {
//                                                Log.i("HTML", "login success");
//                                                // your code
//                                            }
//
//                                            @Override
//                                            public void onFailed(int code) {
//                                                Log.i("HTML", "账号密码错误"+code);
//                                                if (code == 302) {
//                                                    Log.i("HTML", "账号密码错误");
//                                                    // your code
//                                                } else {
//                                                    // your code
//                                                }
//                                            }
//
//                                            @Override
//                                            public void onException(Throwable exception) {
//                                                // your code
//                                            }
//                                        };
//                                //执行手动登录
//                                NIMClient.getService(AuthService.class).login(info).setCallback(callback);

                            }
                        }else {
                            RxToast.showToastShort(o.getMsg());
                        }
                    }
                });

    }

    private  int count = 60;
    public void reTimeSmsCode(){
        count = 60;
        btnClickEndbel.set(false);
        uc.reBtnGetCode.setValue(false);
        addSubscribe(Observable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)    //
                   .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //     .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                          //  Log.d("HTML","doOnSubscribe");
                        // dialog.show();
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long o) throws Exception {
                     //   Log.d("HTML","subscribe");
                        count--;
                        resmsTime.set(count+"s 重新发送");
                        if (o == 59){
                            resmsTime.set("重新获取验证码");
                            btnClickEndbel.set(true);
                            uc.reBtnGetCode.setValue(true);

                        }else {
                            resmsTime.set(count+"s 重新发送");
                        }
                    }
                }));


    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
